﻿#include <iostream>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <thread>
#include <vector>
#include <mutex>
#include <atomic>
#include <string>
#include <sstream>
#include <windows.h>
#include <shellapi.h>
#include <tchar.h>
#include <shlwapi.h>
#include <stdio.h>
#include <deque>
#include <map>

// 链接所需库
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "shlwapi.lib")

// 服务器端口号
const int SERVER_PORT = 18787;

// 引入JSON库的简单实现
namespace simple_json {
    std::string escape(const std::string& s) {
        std::string res;
        for (char c : s) {
            switch (c) {
            case '"': res += "\\\""; break;
            case '\\': res += "\\\\"; break;
            case '\b': res += "\\b"; break;
            case '\f': res += "\\f"; break;
            case '\n': res += "\\n"; break;
            case '\r': res += "\\r"; break;
            case '\t': res += "\\t"; break;
            default: res += c;
            }
        }
        return res;
    }

    std::string create_object(const std::vector<std::pair<std::string, std::string>>& pairs) {
        std::string res = "{";
        for (size_t i = 0; i < pairs.size(); ++i) {
            res += "\"" + escape(pairs[i].first) + "\":" + "\"" + escape(pairs[i].second) + "\"";
            if (i != pairs.size() - 1) {
                res += ",";
            }
        }
        res += "}";
        return res;
    }

    // 改进的get_value函数，支持单引号和双引号的键值对
    std::string get_value(const std::string& json, const std::string& key) {
        // 尝试匹配双引号号包围的键
        std::string double_quoted_key = "\"" + key + "\"";
        size_t key_pos = json.find(double_quoted_key + ":");

        // 如果没找到，尝试匹配单引号号包围的键
        if (key_pos == std::string::npos) {
            std::string single_quoted_key = "'" + key + "'";
            key_pos = json.find(single_quoted_key + ":");
        }

        if (key_pos == std::string::npos) return "";

        // 找到值的开始位置（处理字符串值和非字符串值）
        size_t key_length = key.length() + 2; // 键的长度加上引号
        size_t value_start = key_pos + key_length + 1; // 跳过 "key": 或 'key':

        // 跳过空格
        while (value_start < json.length() && json[value_start] == ' ') {
            value_start++;
        }

        if (value_start >= json.length()) return "";

        // 检查值是否用双引号或单引号包围
        char quote_char = '\0';
        if (json[value_start] == '"' || json[value_start] == '\'') {
            quote_char = json[value_start];
            value_start++; // 跳过开头的引号
        }

        // 如果是字符串值（以引号开头）
        if (quote_char != '\0') {
            size_t value_end = json.find(quote_char, value_start);
            if (value_end == std::string::npos) return "";
            return json.substr(value_start, value_end - value_start);
        }
        // 如果是数组或对象（以[或{开头）
        else if (json[value_start] == '[' || json[value_start] == '{') {
            int bracket_count = 1;
            size_t value_end = value_start + 1;
            char opening_bracket = json[value_start];
            char closing_bracket = (opening_bracket == '[') ? ']' : '}';

            while (value_end < json.length() && bracket_count > 0) {
                if (json[value_end] == opening_bracket) {
                    bracket_count++;
                }
                else if (json[value_end] == closing_bracket) {
                    bracket_count--;
                }
                value_end++;
            }

            if (bracket_count == 0) {
                return json.substr(value_start, value_end - value_start);
            }
            else {
                return ""; // 不匹配的括号
            }
        }
        // 处理其他类型的值（数字、布尔等）
        else {
            size_t value_end = json.find_first_of(",}] ", value_start);
            if (value_end == std::string::npos) {
                value_end = json.length();
            }
            return json.substr(value_start, value_end - value_start);
        }
    }

    // 改进的数组解析函数，能正确处理包含单引号的JSON数组
    std::vector<std::string> parse_array(const std::string& json, const std::string& array_key) {
        std::vector<std::string> elements;

        // 获取数组的原始字符串
        std::string array_str = get_value(json, array_key);
        if (array_str.empty() || array_str[0] != '[' || array_str.back() != ']') {
            return elements; // 不是有效的数组
        }

        // 提取数组内容（去掉首尾的[]）
        std::string array_content = array_str.substr(1, array_str.length() - 2);
        size_t pos = 0;
        const size_t content_len = array_content.length();

        // 跳过开头的空格
        while (pos < content_len && array_content[pos] == ' ') {
            pos++;
        }

        while (pos < content_len) {
            if (array_content[pos] == '{') { // 处理对象元素
                int brace_count = 1;
                size_t element_end = pos + 1;

                while (element_end < content_len && brace_count > 0) {
                    // 处理引号内的内容，避免错误识别括号
                    if (array_content[element_end] == '"' || array_content[element_end] == '\'') {
                        char quote_char = array_content[element_end];
                        element_end++;
                        while (element_end < content_len) {
                            if (array_content[element_end] == quote_char &&
                                (element_end == 0 || array_content[element_end - 1] != '\\')) {
                                break;
                            }
                            element_end++;
                        }
                    }
                    else if (array_content[element_end] == '{') {
                        brace_count++;
                    }
                    else if (array_content[element_end] == '}') {
                        brace_count--;
                    }
                    element_end++;
                }

                if (brace_count == 0) {
                    elements.push_back(array_content.substr(pos, element_end - pos));
                    pos = element_end;
                }
                else {
                    break; // 括号不匹配，退出解析
                }
            }
            else if (array_content[pos] == '"' || array_content[pos] == '\'') { // 处理字符串元素（双引号或单引号）
                char quote_char = array_content[pos];
                size_t element_end = pos + 1;
                bool escaped = false;

                while (element_end < content_len) {
                    if (!escaped && array_content[element_end] == quote_char) {
                        element_end++;
                        break;
                    }
                    escaped = (!escaped && array_content[element_end] == '\\');
                    element_end++;
                }

                elements.push_back(array_content.substr(pos, element_end - pos));
                pos = element_end;
            }
            else { // 处理其他类型元素（数字、布尔等）
                size_t element_end = array_content.find_first_of(", ]", pos);
                if (element_end == std::string::npos) {
                    element_end = content_len;
                }

                elements.push_back(array_content.substr(pos, element_end - pos));
                pos = element_end;
            }

            // 跳过逗号和空格
            while (pos < content_len && (array_content[pos] == ',' || array_content[pos] == ' ')) {
                pos++;
            }
        }

        return elements;
    }
}

// 键盘按键到虚拟键码的映射表
// 同时支持小写和大写字母，大写字母会自动处理Shift键
const std::map<std::string, WORD> KEY_NAME_TO_VK = {
    // 小写字母
    {"a", 'A'}, {"b", 'B'}, {"c", 'C'}, {"d", 'D'}, {"e", 'E'}, {"f", 'F'}, {"g", 'G'},
    {"h", 'H'}, {"i", 'I'}, {"j", 'J'}, {"k", 'K'}, {"l", 'L'}, {"m", 'M'}, {"n", 'N'},
    {"o", 'O'}, {"p", 'P'}, {"q", 'Q'}, {"r", 'R'}, {"s", 'S'}, {"t", 'T'}, {"u", 'U'},
    {"v", 'V'}, {"w", 'W'}, {"x", 'X'}, {"y", 'Y'}, {"z", 'Z'},
    // 大写字母
    {"A", 'A'}, {"B", 'B'}, {"C", 'C'}, {"D", 'D'}, {"E", 'E'}, {"F", 'F'}, {"G", 'G'},
    {"H", 'H'}, {"I", 'I'}, {"J", 'J'}, {"K", 'K'}, {"L", 'L'}, {"M", 'M'}, {"N", 'N'},
    {"O", 'O'}, {"P", 'P'}, {"Q", 'Q'}, {"R", 'R'}, {"S", 'S'}, {"T", 'T'}, {"U", 'U'},
    {"V", 'V'}, {"W", 'W'}, {"X", 'X'}, {"Y", 'Y'}, {"Z", 'Z'},
    // 数字
    {"0", '0'}, {"1", '1'}, {"2", '2'}, {"3", '3'}, {"4", '4'},
    {"5", '5'}, {"6", '6'}, {"7", '7'}, {"8", '8'}, {"9", '9'},
    // 功能键
    {"f1", VK_F1}, {"f2", VK_F2}, {"f3", VK_F3}, {"f4", VK_F4},
    {"f5", VK_F5}, {"f6", VK_F6}, {"f7", VK_F7}, {"f8", VK_F8},
    {"f9", VK_F9}, {"f10", VK_F10}, {"f11", VK_F11}, {"f12", VK_F12},
    // 编辑键
    {"insert", VK_INSERT}, {"delete", VK_DELETE}, {"home", VK_HOME},
    {"end", VK_END}, {"pgup", VK_PRIOR}, {"pgdn", VK_NEXT},
    // 方向键
    {"up", VK_UP}, {"down", VK_DOWN}, {"left", VK_LEFT}, {"right", VK_RIGHT},
    // 其他常用键
    {"space", VK_SPACE}, {"enter", VK_RETURN}, {"esc", VK_ESCAPE},
    {"tab", VK_TAB}, {"backspace", VK_BACK}, {"shift", VK_SHIFT},
    {"ctrl", VK_CONTROL}, {"alt", VK_MENU}, {"capslock", VK_CAPITAL},
    {"numlock", VK_NUMLOCK}, {"scrolllock", VK_SCROLL},
    // 数字键盘
    {"+", VK_ADD}, {"-", VK_SUBTRACT}, {"*", VK_MULTIPLY}, {"/", VK_DIVIDE},
    {".", VK_DECIMAL}, {",", VK_OEM_COMMA}, {";", VK_OEM_1}, {"=", VK_OEM_PLUS},
    {"[", VK_OEM_4}, {"]", VK_OEM_6}, {"'", VK_OEM_7}, {"\\", VK_OEM_5},
    {"`", VK_OEM_3}, {"-", VK_OEM_MINUS}, {"/", VK_OEM_2}
};

// 键盘按键任务结构 - 增加afterInterval属性
struct KeyPressTask {
    std::string key;    // 按键（支持普通字符和特殊按键如f10,insert等）
    int press_count;    // 按键次数
    int interval;       // 按键间隔(毫秒)
    int after_interval; // 每次循环结束后额外等待时间(毫秒)
};

// 全局共享变量 - 服务器状态
char ONE_OR_MUTIPLE = 'S';  // 'S'表示单体(Single), 'A'表示AOE(Area of Effect)
char ZZZ = 'N';             // 'N'表示未终止, 'Y'表示已终止
char MOUSE_UP_OR_DOWN = 'U';// 'U'表示鼠标抬起(Up), 'D'表示鼠标按下(Down)
char HEARTBEAT_COLOR = 'R'; // 'R'表示红色(Red), 'G'表示绿色(Green) - 心跳颜色控制变量

// 用于保护全局变量读写的互斥锁
std::mutex globalVarsMutex;

// 线程安全的客户端计数和相关互斥锁
std::atomic<int> clientCount(0);
std::mutex coutMutex;
std::mutex threadMutex;
std::vector<std::thread> clientThreads;

// 键盘任务队列及相关锁
std::deque<std::vector<KeyPressTask>> keyTaskQueue;
std::mutex keyTaskMutex;
std::condition_variable keyTaskCV;
std::atomic<bool> keyThreadRunning(false);

// 服务器监听套接字和运行状态
SOCKET listenSocket = INVALID_SOCKET;
std::atomic<bool> serverRunning(false);

// 界面相关全局变量
HINSTANCE hInst;
TCHAR szTitle[256];         // 动态设置窗口标题
TCHAR szWindowClass[] = _T("TRANSPARENT_TOPMOST_VBS_CLASS");
TCHAR szVBSFilePath[MAX_PATH] = _T("C:\\Users\\Hasee\\Desktop\\ddyy.vbs");
static HBRUSH hRedBrush;    // 红色画刷
static HBRUSH hGreenBrush;  // 绿色画刷
static HBRUSH hWindowRedBrush;  // 窗口红色背景画刷
static HBRUSH hWindowGreenBrush; // 窗口绿色背景画刷
static HWND hCheckbox;
static HWND hCoordLabel;
static HWND hSizeInput;
static HWND hRLabel, hGLabel, hBLabel;
static HWND hSizeLabel;
static BOOL bShowCoords = FALSE;
static int hSize = 10;
static HWND hBtnExecute;    // 执行按钮的句柄，用于更新UI
static HWND hEventLog;      // 事件日志显示控件

// 输入监控相关全局变量
HHOOK hMouseHook;
HHOOK hKeyboardHook;
std::wstring eventLog;
// 用于限制鼠标移动事件的频率，避免日志刷屏
DWORD lastMouseMoveTime = 0;
const DWORD MOUSE_MOVE_DELAY = 500; // 500毫秒记录一次移动

// 函数声明
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
void ExecuteExistingVBScript();
BOOL IsFileExists(LPCTSTR szPath);
void UpdateMouseCoordinates();
void StartMouseTracking(HWND hWnd);
void StopMouseTracking(HWND hWnd);
COLORREF GetAverageColor(int x, int y, int size);
void PredefinedFunction();
void handleClient(SOCKET clientSocket);
void serverListenThread(HWND hWnd);
void startServer(HWND hWnd);
void stopServer();
void UpdateButtonColor();
void UpdateWindowBackgroundColor(HWND hWnd);
void OnDrawFromPython();
void OnDrawTextFromPython();
void keyPressThread();
void simulateKeyPress(const std::string& key, int pressCount, int intervalMs, int afterIntervalMs);
WORD getVirtualKeyCode(const std::string& keyName);
// 添加新函数声明
bool isDigitString(const std::string& str);
void SwitchToEnglishInputMethod();

// 输入监控相关函数声明
LRESULT CALLBACK MouseHookProc(int, WPARAM, LPARAM);
LRESULT CALLBACK KeyboardHookProc(int, WPARAM, LPARAM);
void UpdateEventLog(const std::wstring& event);
wchar_t GetCharFromKey(DWORD vkCode, bool isExtended);
void SetHook();
void Unhook();

// 在指定位置绘制文字并返回包含文字的图像像素数据
std::vector<BYTE> drawText(const std::wstring& text,
    int x = 10, int y = 10,
    COLORREF textColor = RGB(255, 0, 0),  // 默认红色文字
    const wchar_t* fontName = L"Arial",
    int fontSize = 24,
    int width = 0, int height = 0) {
    // 获取桌面窗口DC
    HDC hdcScreen = GetDC(NULL);
    if (!hdcScreen) return {};

    // 如果未指定宽高，使用默认值
    int w = width;
    int h = height;

    // 如果未指定宽高，计算文本所需尺寸
    if (w == 0 || h == 0) {
        // 创建临时DC用于测量文本
        HDC hdcTemp = CreateCompatibleDC(hdcScreen);
        HFONT hFont = CreateFont(fontSize, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,
            DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
            DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, fontName);
        HGDIOBJ hOldFont = SelectObject(hdcTemp, hFont);

        // 测量文本尺寸
        RECT rect = { 0, 0, 0, 0 };
        DrawText(hdcTemp, text.c_str(), -1, &rect, DT_CALCRECT);

        // 设置默认宽高（在文本尺寸基础上增加边距）
        if (w == 0) w = rect.right - rect.left + 20;
        if (h == 0) h = rect.bottom - rect.top + 20;

        // 清理临时资源
        SelectObject(hdcTemp, hOldFont);
        DeleteObject(hFont);
        DeleteDC(hdcTemp);
    }

    // 创建兼容DC和位图
    HDC hdcMem = CreateCompatibleDC(hdcScreen);
    HBITMAP hbmMem = CreateCompatibleBitmap(hdcScreen, w, h);
    if (!hdcMem || !hbmMem) {
        DeleteDC(hdcMem);
        DeleteObject(hbmMem);
        ReleaseDC(NULL, hdcScreen);
        return {};
    }

    // 保存原始位图
    HGDIOBJ hbmOld = SelectObject(hdcMem, hbmMem);

    // 填充背景为白色
    HBRUSH hWhiteBrush = CreateSolidBrush(RGB(255, 255, 255));
    RECT bgRect = { 0, 0, w, h };
    FillRect(hdcMem, &bgRect, hWhiteBrush);
    DeleteObject(hWhiteBrush);

    // 创建字体
    HFONT hFont = CreateFont(fontSize, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,
        DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
        DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, fontName);
    if (!hFont) {
        // 清理资源
        SelectObject(hdcMem, hbmOld);
        DeleteObject(hbmMem);
        DeleteDC(hdcMem);
        ReleaseDC(NULL, hdcScreen);
        return {};
    }

    // 选择字体和文本颜色
    HGDIOBJ hOldFont = SelectObject(hdcMem, hFont);
    SetTextColor(hdcMem, textColor);
    SetBkMode(hdcMem, TRANSPARENT);  // 透明背景

    // 绘制文本
    RECT textRect = { x, y, w, h };
    DrawText(hdcMem, text.c_str(), -1, &textRect, DT_LEFT | DT_TOP);

    // 获取位图数据
    BITMAP bmp;
    GetObject(hbmMem, sizeof(bmp), &bmp);

    // 计算像素数据大小
    DWORD dwBmpSize = bmp.bmWidthBytes * bmp.bmHeight;

    // 分配内存存储像素数据
    std::vector<BYTE> bitmapBits(dwBmpSize);

    // 读取位图数据
    BITMAPINFOHEADER bi;
    bi.biSize = sizeof(BITMAPINFOHEADER);
    bi.biWidth = bmp.bmWidth;
    bi.biHeight = bmp.bmHeight;
    bi.biPlanes = 1;
    bi.biBitCount = bmp.bmBitsPixel;
    bi.biCompression = BI_RGB;
    bi.biSizeImage = 0;
    bi.biXPelsPerMeter = 0;
    bi.biYPelsPerMeter = 0;
    bi.biClrUsed = 0;
    bi.biClrImportant = 0;

    GetDIBits(hdcMem, hbmMem, 0, (UINT)bmp.bmHeight, bitmapBits.data(),
        (BITMAPINFO*)&bi, DIB_RGB_COLORS);

    // 清理资源
    SelectObject(hdcMem, hOldFont);
    DeleteObject(hFont);
    SelectObject(hdcMem, hbmOld);
    DeleteObject(hbmMem);
    DeleteDC(hdcMem);
    ReleaseDC(NULL, hdcScreen);

    return bitmapBits;
}

// 绘制矩形并返回截图的像素数据
std::vector<BYTE> drawRec(int argw = 0, int argh = 0,
    std::pair<int, int> argtopleft = { 0, 0 },
    COLORREF argColor = 0, int width = 1) {
    // 获取桌面窗口DC（0表示桌面窗口）
    HDC hdcScreen = GetDC(NULL);
    if (!hdcScreen) return {};

    // 获取显示器信息以确定默认尺寸
    MONITORINFOEX monitorInfo;
    monitorInfo.cbSize = sizeof(MONITORINFOEX);
    EnumDisplayMonitors(hdcScreen, NULL, [](HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) -> BOOL {
        MONITORINFOEX* pInfo = reinterpret_cast<MONITORINFOEX*>(dwData);
        GetMonitorInfo(hMonitor, pInfo);
        return FALSE; // 只获取第一个显示器
        }, reinterpret_cast<LPARAM>(&monitorInfo));

    // 确定截图尺寸
    int w = (argw == 0) ? (monitorInfo.rcMonitor.right - monitorInfo.rcMonitor.left) : argw;
    int h = (argh == 0) ? (monitorInfo.rcMonitor.bottom - monitorInfo.rcMonitor.top) : argh;

    // 确定截图起始位置
    int tx = (argtopleft.first <= 0) ? 0 : argtopleft.first;
    int ty = (argtopleft.second <= 0) ? 0 : argtopleft.second;

    // 创建兼容DC和位图用于截图
    HDC hdcMem = CreateCompatibleDC(hdcScreen);
    HBITMAP hbmMem = CreateCompatibleBitmap(hdcScreen, w, h);
    if (!hdcMem || !hbmMem) {
        DeleteDC(hdcMem);
        DeleteObject(hbmMem);
        ReleaseDC(NULL, hdcScreen);
        return {};
    }

    // 保存原始位图以便恢复
    HGDIOBJ hbmOld = SelectObject(hdcMem, hbmMem);

    // 执行截图
    BitBlt(hdcMem, 0, 0, w, h, hdcScreen, tx, ty, SRCCOPY);

    // 绘制矩形框 - 使用红色以便更容易看到
    HPEN hPen = CreatePen(PS_SOLID, width, argColor == 0 ? RGB(255, 0, 0) : argColor);
    HPEN hPenOld = static_cast<HPEN>(SelectObject(hdcScreen, hPen));

    // 使用透明画刷
    HBRUSH hBrush = static_cast<HBRUSH>(GetStockObject(NULL_BRUSH));
    HBRUSH hBrushOld = static_cast<HBRUSH>(SelectObject(hdcScreen, hBrush));

    // 绘制矩形
    Rectangle(hdcScreen, tx - 1, ty - 1, tx + w + 2, ty + h + 2);

    // 恢复原始GDI对象
    SelectObject(hdcScreen, hPenOld);
    SelectObject(hdcScreen, hBrushOld);

    // 获取位图数据
    BITMAP bmp;
    GetObject(hbmMem, sizeof(bmp), &bmp);

    // 计算像素数据大小
    DWORD dwBmpSize = bmp.bmWidthBytes * bmp.bmHeight;

    // 分配内存存储像素数据
    std::vector<BYTE> bitmapBits(dwBmpSize);

    // 读取位图数据
    BITMAPINFOHEADER bi;
    bi.biSize = sizeof(BITMAPINFOHEADER);
    bi.biWidth = bmp.bmWidth;
    bi.biHeight = bmp.bmHeight;
    bi.biPlanes = 1;
    bi.biBitCount = bmp.bmBitsPixel;
    bi.biCompression = BI_RGB;
    bi.biSizeImage = 0;
    bi.biXPelsPerMeter = 0;
    bi.biYPelsPerMeter = 0;
    bi.biClrUsed = 0;
    bi.biClrImportant = 0;

    GetDIBits(hdcMem, hbmMem, 0, (UINT)bmp.bmHeight, bitmapBits.data(),
        (BITMAPINFO*)&bi, DIB_RGB_COLORS);

    // 清理资源
    SelectObject(hdcMem, hbmOld);
    DeleteObject(hbmMem);
    DeleteDC(hdcMem);
    DeleteObject(hPen);
    ReleaseDC(NULL, hdcScreen);

    return bitmapBits;
}

// 更新按钮颜色
void UpdateButtonColor() {
    if (hBtnExecute) {
        // 根据当前心跳颜色设置按钮画刷
        HBRUSH currentBrush = (HEARTBEAT_COLOR == 'R') ? hRedBrush : hGreenBrush;

        // 强制按钮重绘
        InvalidateRect(hBtnExecute, NULL, TRUE);
        UpdateWindow(hBtnExecute);
    }
}

// 按钮点击事件处理函数
void OnDrawFromPython() {
    // 秒数个位为奇数时不执行任何操作
    std::vector<BYTE> bitmapData = drawRec(
        20, 20,       // 宽度和高度
        { 50, 50 },   // 左上角位置
        RGB(255, 0, 0), // 颜色（红色）
        10               // 线宽
    );
}

// 按钮点击事件处理函数
void OnDrawTextFromPython() {
    drawText(L"Hello World!", 10, 10, RGB(255, 0, 0), L"Arial", 24);
}

// 更新窗口背景色
void UpdateWindowBackgroundColor(HWND hWnd) {
    if (hWnd) {
        // 根据当前心跳颜色选择窗口背景画刷
        HBRUSH currentBrush;
        {
            std::lock_guard<std::mutex> lock(globalVarsMutex);
            currentBrush = (HEARTBEAT_COLOR == 'R') ? hWindowRedBrush : hWindowGreenBrush;
        }

        // 设置窗口背景刷并刷新
        SetClassLongPtr(hWnd, GCLP_HBRBACKGROUND, (LONG_PTR)currentBrush);
        InvalidateRect(hWnd, NULL, TRUE);
        UpdateWindow(hWnd);
    }
}

// 将按键名称转换为虚拟键码
WORD getVirtualKeyCode(const std::string& keyName) {
    // 直接查找映射表，不转换大小写，以便区分大小写字母
    auto it = KEY_NAME_TO_VK.find(keyName);
    if (it != KEY_NAME_TO_VK.end()) {
        return it->second;
    }

    // 如果找不到匹配的特殊键，尝试直接转换为ASCII码
    if (keyName.length() == 1) {
        return static_cast<WORD>(keyName[0]);
    }

    // 未知按键
    return 0;
}

// 模拟键盘按键 - 增加afterIntervalMs参数
void simulateKeyPress(const std::string& key, int pressCount, int intervalMs, int afterIntervalMs) {
    // 获取虚拟键码
    WORD keyCode = getVirtualKeyCode(key);

    if (keyCode == 0) {
        std::lock_guard<std::mutex> coutLock(coutMutex);
        std::cout << "未知按键: " << key << std::endl;
        return;
    }

    // 对于大写字母，需要按下Shift键
    bool needShift = (key.length() == 1 && isalpha(key[0]) && isupper(key[0]));

    if (needShift) {
        keybd_event(VK_SHIFT, 0, 0, 0);
    }

    // 执行按键操作
    for (int i = 0; i < pressCount; ++i) {
        // 按下键
        keybd_event(keyCode, 0, 0, 0);
        Sleep(50); // 按键按下时间

        // 释放键
        keybd_event(keyCode, 0, KEYEVENTF_KEYUP, 0);

        // 如果不是最后一次按键，等待指定间隔
        if (i < pressCount - 1) {
            Sleep(intervalMs);
        }
    }

    // 释放Shift键（如果之前按下）
    if (needShift) {
        keybd_event(VK_SHIFT, 0, KEYEVENTF_KEYUP, 0);
    }

    // 在整个循环结束后等待指定的额外时间
    if (afterIntervalMs > 0) {
        {
            std::lock_guard<std::mutex> coutLock(coutMutex);
            std::cout << "按键循环结束，额外等待 " << afterIntervalMs << "ms" << std::endl;
        }
        Sleep(afterIntervalMs);
    }
}

// 键盘按键处理线程
void keyPressThread() {
    while (keyThreadRunning) {
        std::vector<KeyPressTask> tasks;

        // 等待任务
        std::unique_lock<std::mutex> lock(keyTaskMutex);
        keyTaskCV.wait(lock, [] { return !keyTaskQueue.empty() || !keyThreadRunning; });

        if (!keyThreadRunning) break;

        // 获取任务
        tasks = keyTaskQueue.front();
        keyTaskQueue.pop_front();
        lock.unlock();

        // 执行任务
        {
            std::lock_guard<std::mutex> coutLock(coutMutex);
            std::cout << "开始执行键盘任务，共 " << tasks.size() << " 个按键序列" << std::endl;
        }

        for (const auto& task : tasks) {
            {
                std::lock_guard<std::mutex> coutLock(coutMutex);
                std::cout << "执行按键: " << task.key << ", 次数: " << task.press_count
                    << ", 间隔: " << task.interval << "ms, 循环后等待: " << task.after_interval << "ms" << std::endl;
            }

            // 传递after_interval参数
            simulateKeyPress(task.key, task.press_count, task.interval, task.after_interval);

            // 不同按键序列之间等待500ms
            if (&task != &tasks.back()) {
                Sleep(500);
            }
        }

        {
            std::lock_guard<std::mutex> coutLock(coutMutex);
            std::cout << "键盘任务执行完成" << std::endl;
        }
    }
}

// 检查字符串是否为纯数字
bool isDigitString(const std::string& str) {
    for (char c : str) {
        if (!isdigit(c)) {
            return false;
        }
    }
    return !str.empty();
}

// 切换到英文输入法
void SwitchToEnglishInputMethod() {
    // 获取当前线程ID
    DWORD dwThreadId = GetWindowThreadProcessId(GetForegroundWindow(), NULL);

    // 尝试切换到英文输入法
    // 方法1: 使用系统默认的英文输入法
    HKL hklEnglish = LoadKeyboardLayout(L"00000409", KLF_ACTIVATE);
    if (hklEnglish) {
        ActivateKeyboardLayout(hklEnglish, KLF_SETFORPROCESS);
        return;
    }

    // 方法2: 如果找不到英文输入法，尝试切换到第一个可用的输入法
    HKL* pKeyboards = NULL;
    int nKeyboards = GetKeyboardLayoutList(0, NULL);
    if (nKeyboards > 0) {
        pKeyboards = new HKL[nKeyboards];
        nKeyboards = GetKeyboardLayoutList(nKeyboards, pKeyboards);

        if (nKeyboards > 0) {
            ActivateKeyboardLayout(pKeyboards[0], KLF_SETFORPROCESS);
        }

        delete[] pKeyboards;
    }
}

// 处理客户端连接的函数
void handleClient(SOCKET clientSocket) {
    int clientId = ++clientCount;

    {
        std::lock_guard<std::mutex> lock(coutMutex);
        std::cout << "客户端 " << clientId << " 已连接" << std::endl;
    }

    char buffer[1024];
    int bytesReceived;

    // 设置客户端套接字为非阻塞模式
    u_long mode = 1;
    ioctlsocket(clientSocket, FIONBIO, &mode);

    while (serverRunning) {
        // 接收客户端数据
        bytesReceived = recv(clientSocket, buffer, sizeof(buffer) - 1, 0);

        if (bytesReceived > 0) {
            buffer[bytesReceived] = '\0';

            {
                std::lock_guard<std::mutex> lock(coutMutex);
                std::cout << "从客户端 " << clientId << " 接收: " << buffer << std::endl;
            }

            // 解析JSON命令
            std::string command(buffer);
            std::string mode = simple_json::get_value(command, "mode");
            std::string response;

            if (mode == "WRITE") {
                // 写入模式 - 修改服务器变量
                std::string var = simple_json::get_value(command, "variable");
                std::string value = simple_json::get_value(command, "value");

                bool success = false;
                std::string message;
                bool updateColor = false;  // 标记是否需要更新颜色

                {
                    std::lock_guard<std::mutex> lock(globalVarsMutex);

                    if (var == "skill_type") {
                        if (value == "A" || value == "S") {
                            ONE_OR_MUTIPLE = value[0];
                            success = true;
                            message = "技能类型已更新";
                        }
                        else {
                            message = "无效的技能类型值，必须是'A'或'S'";
                        }
                    }
                    else if (var == "terminate_status") {
                        if (value == "Y" || value == "N") {
                            ZZZ = value[0];
                            success = true;
                            message = "终止状态已更新";
                        }
                        else {
                            message = "无效的终止状态值，必须是'Y'或'N'";
                        }
                    }
                    else if (var == "mouse_status") {
                        if (value == "U" || value == "D") {
                            MOUSE_UP_OR_DOWN = value[0];
                            success = true;
                            message = "鼠标状态已更新";
                        }
                        else {
                            message = "无效的鼠标状态值，必须是'U'或'D'";
                        }
                    }
                    // 处理心跳颜色控制
                    else if (var == "heartbeat_color") {
                        // 不管设置什么颜色，都需要在桌面把框画出来
                        OnDrawFromPython();
                        OnDrawTextFromPython();
                        // 根据接收到的具体值设置颜色
                        if (value == "R" || value == "G") {
                            HEARTBEAT_COLOR = value[0];
                            success = true;
                            message = "心跳颜色已设置为" + std::string((HEARTBEAT_COLOR == 'R') ? "红色" : "绿色");
                            updateColor = true;  // 需要更新颜色
                        }
                        else {
                            message = "无效的颜色值，必须是'R'或'G'";
                        }
                    }
                    else {
                        message = "未知变量: " + var;
                    }
                }

                // 如果需要更新颜色，使用SendMessage同步调用UI更新
                if (updateColor && hBtnExecute) {
                    // 使用SendMessage确保在主线程同步执行颜色更新
                    SendMessage(hBtnExecute, WM_USER + 1, 0, 0);
                    // 同时更新窗口背景色
                    SendMessage(GetParent(hBtnExecute), WM_USER + 2, 0, 0);
                }

                // 构建写入操作的响应
                response = simple_json::create_object({
                    {"status", success ? "success" : "error"},
                    {"message", message},
                    {"skill_type", std::string(1, ONE_OR_MUTIPLE)},
                    {"terminate_status", std::string(1, ZZZ)},
                    {"mouse_status", std::string(1, MOUSE_UP_OR_DOWN)},
                    {"heartbeat_color", std::string(1, HEARTBEAT_COLOR)},  // 返回当前心跳颜色
                    {"heartbeat_color_desc", (HEARTBEAT_COLOR == 'R' ? "红色" : "绿色")}  // 颜色描述
                    });
            }
            else if (mode == "READ") {
                // 读取模式 - 获取服务器变量
                {
                    std::lock_guard<std::mutex> lock(globalVarsMutex);
                    response = simple_json::create_object({
                        {"status", "success"},
                        {"message", "变量读取成功"},
                        {"skill_type", std::string(1, ONE_OR_MUTIPLE)},
                        {"skill_type_desc", (ONE_OR_MUTIPLE == 'A' ? "AOE" : "单体")},
                        {"terminate_status", std::string(1, ZZZ)},
                        {"terminate_status_desc", (ZZZ == 'Y' ? "已终止" : "运行中")},
                        {"mouse_status", std::string(1, MOUSE_UP_OR_DOWN)},
                        {"mouse_status_desc", (MOUSE_UP_OR_DOWN == 'D' ? "按下" : "抬起")},
                        {"heartbeat_color", std::string(1, HEARTBEAT_COLOR)},  // 返回当前心跳颜色
                        {"heartbeat_color_desc", (HEARTBEAT_COLOR == 'R' ? "红色" : "绿色")}  // 颜色描述
                        });
                }
            }
            else if (mode == "RUN") {
                // 运行模式 - 执行键盘操作
                std::vector<std::string> keyActions = simple_json::parse_array(command, "value");

                if (keyActions.empty()) {
                    response = simple_json::create_object({
                        {"status", "error"},
                        {"message", "未找到有效的按键序列"}
                        });
                }
                else {
                    std::vector<KeyPressTask> tasks;
                    bool valid = true;

                    // 解析每个按键任务，增加afterInterval的解析
                    for (const std::string& action : keyActions) {
                        std::string key = simple_json::get_value(action, "key");
                        std::string countStr = simple_json::get_value(action, "times");
                        std::string intervalStr = simple_json::get_value(action, "interval");
                        std::string afterIntervalStr = simple_json::get_value(action, "afterInterval");

                        // afterInterval可选，如果未提供默认为0
                        if (afterIntervalStr.empty()) {
                            afterIntervalStr = "0";
                        }

                        if (key.empty() || countStr.empty() || intervalStr.empty()) {
                            valid = false;
                            break;
                        }

                        // 检查数字类型
                        if (!isDigitString(countStr)) {
                            valid = false;
                            response = simple_json::create_object({
                                {"status", "error"},
                                {"message", "按键次数必须是数字: " + countStr}
                                });
                            break;
                        }

                        if (!isDigitString(intervalStr)) {
                            valid = false;
                            response = simple_json::create_object({
                                {"status", "error"},
                                {"message", "按键间隔必须是数字: " + intervalStr}
                                });
                            break;
                        }

                        if (!isDigitString(afterIntervalStr)) {
                            valid = false;
                            response = simple_json::create_object({
                                {"status", "error"},
                                {"message", "循环后等待时间必须是数字: " + afterIntervalStr}
                                });
                            break;
                        }

                        int count = std::stoi(countStr);
                        int interval = std::stoi(intervalStr);
                        int afterInterval = std::stoi(afterIntervalStr);

                        if (count <= 0 || interval < 0 || afterInterval < 0) {
                            valid = false;
                            break;
                        }

                        // 添加after_interval到任务中
                        tasks.push_back({ key, count, interval, afterInterval });
                    }

                    if (!valid) {
                        // 如果已经设置了response（如数字类型错误），则使用已有的response
                        if (response.empty()) {
                            response = simple_json::create_object({
                                {"status", "error"},
                                {"message", "按键序列格式无效"}
                                });
                        }
                    }
                    else {
                        // 将任务加入队列
                        {
                            std::lock_guard<std::mutex> lock(keyTaskMutex);
                            keyTaskQueue.push_back(tasks);
                            keyTaskCV.notify_one();
                        }

                        response = simple_json::create_object({
                            {"status", "success"},
                            {"message", "已添加键盘任务，共 " + std::to_string(tasks.size()) + " 个按键序列"},
                            {"task_count", std::to_string(keyTaskQueue.size())}
                            });
                        {
                            std::lock_guard<std::mutex> coutLock(coutMutex);
                            std::cout << "客户端 " << clientId << " 添加了键盘任务" << std::endl;
                        }
                    }
                }
            }
            else {
                // 未知模式
                response = simple_json::create_object({
                    {"status", "error"},
                    {"message", "无效的模式，必须是'READ'、'WRITE'或'RUN'"}
                    });
            }

            // 发送响应给客户端
            send(clientSocket, response.c_str(), response.length(), 0);

            {
                std::lock_guard<std::mutex> lock(coutMutex);
                std::cout << "发送给客户端 " << clientId << ": " << response << std::endl;
            }
        }
        else if (bytesReceived == 0) {
            // 客户端正常关闭连接
            break;
        }
        else {
            // 处理非阻塞模式下的WSAEWOULDBLOCK错误
            int error = WSAGetLastError();
            if (error != WSAEWOULDBLOCK) {
                std::lock_guard<std::mutex> lock(coutMutex);
                std::cout << "客户端 " << clientId << " 发生错误，错误代码: " << error << std::endl;
                break;
            }

            // 短暂休眠，避免CPU占用过高
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
        }
    }

    {
        std::lock_guard<std::mutex> lock(coutMutex);
        std::cout << "客户端 " << clientId << " 已断开连接" << std::endl;
    }

    // 关闭客户端套接字
    closesocket(clientSocket);
    clientCount--;
}

// 服务器监听线程函数
void serverListenThread(HWND hWnd) {
    WSADATA wsaData;
    int iResult;

    // 初始化Winsock
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != 0) {
        std::cerr << "WSAStartup 失败: " << iResult << std::endl;
        SendMessage(hWnd, WM_CLOSE, 0, 0);
        return;
    }

    // 创建监听套接字
    listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (listenSocket == INVALID_SOCKET) {
        std::cerr << "socket 创建失败: " << WSAGetLastError() << std::endl;
        WSACleanup();
        SendMessage(hWnd, WM_CLOSE, 0, 0);
        return;
    }

    // 设置服务器地址和端口
    sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = INADDR_ANY;
    serverAddr.sin_port = htons(SERVER_PORT);  // 使用抽象的端口变量

    // 绑定套接字
    iResult = bind(listenSocket, (SOCKADDR*)&serverAddr, sizeof(serverAddr));
    if (iResult == SOCKET_ERROR) {
        std::cerr << "绑定失败: " << WSAGetLastError() << std::endl;
        closesocket(listenSocket);
        WSACleanup();
        SendMessage(hWnd, WM_CLOSE, 0, 0);
        return;
    }

    // 将监听套接字设置为非阻塞模式
    u_long mode = 1;
    iResult = ioctlsocket(listenSocket, FIONBIO, &mode);
    if (iResult == SOCKET_ERROR) {
        std::cerr << "设置非阻塞模式失败: " << WSAGetLastError() << std::endl;
        closesocket(listenSocket);
        WSACleanup();
        SendMessage(hWnd, WM_CLOSE, 0, 0);
        return;
    }

    // 开始监听
    if (listen(listenSocket, SOMAXCONN) == SOCKET_ERROR) {
        std::cerr << "监听失败: " << WSAGetLastError() << std::endl;
        closesocket(listenSocket);
        WSACleanup();
        SendMessage(hWnd, WM_CLOSE, 0, 0);
        return;
    }

    {
        std::lock_guard<std::mutex> lock(coutMutex);
        std::cout << "服务器已启动，监听端口 " << SERVER_PORT << "..." << std::endl;  // 使用端口变量
        std::cout << "支持的JSON命令格式:" << std::endl;
        std::cout << "读取模式: {\"mode\":\"READ\"} 或 {'mode':'READ'}" << std::endl;
        std::cout << "写入模式: {\"mode\":\"WRITE\",\"variable\":\"变量名\",\"value\":\"值\"} 或 {'mode':'WRITE','variable':'变量名','value':'值'}" << std::endl;
        std::cout << "运行模式: {\"mode\":\"RUN\",\"keys\":[{\"key\":\"按键\",\"times\":\"次数\",\"interval\":\"间隔(ms)\",\"afterInterval\":\"循环后等待(ms)\"},...]} 或 " << std::endl;
        std::cout << "         {'mode':'RUN','keys':[{'key':'按键','times':'次数','interval':'间隔(ms)','afterInterval':'循环后等待(ms)'},...]}" << std::endl;
        std::cout << "可用变量: skill_type(A/S), terminate_status(Y/N), mouse_status(U/D), heartbeat_color(R/G)" << std::endl;
        std::cout << "支持的按键: a-z, A-Z, 0-9, f1-f12, insert, delete, home, end, pgup, pgdn, up, down, left, right等" << std::endl;
    }

    // 更新窗口标题，指示服务器已启动和实际端口号
    TCHAR runningTitle[256];
    _stprintf_s(runningTitle, _T("顶层轰炸机:运行中(%d)"), SERVER_PORT);
    SetWindowText(hWnd, runningTitle);

    // 启动键盘处理线程
    keyThreadRunning = true;
    std::thread(keyPressThread).detach();

    // 主循环，接受客户端连接
    while (serverRunning) {
        sockaddr_in clientAddr;
        int clientAddrSize = sizeof(clientAddr);

        // 接受客户端连接
        SOCKET clientSocket = accept(listenSocket, (SOCKADDR*)&clientAddr, &clientAddrSize);

        if (clientSocket == INVALID_SOCKET) {
            int error = WSAGetLastError();
            if (error != WSAEWOULDBLOCK) {
                std::lock_guard<std::mutex> lock(coutMutex);
                std::cerr << "接受连接失败: " << error << std::endl;
            }
        }
        else {
            // 创建新线程处理客户端
            std::lock_guard<std::mutex> lock(threadMutex);
            clientThreads.emplace_back(handleClient, clientSocket);
            clientThreads.back().detach();
        }

        // 清理已完成的线程
        std::lock_guard<std::mutex> lock(threadMutex);
        clientThreads.erase(
            std::remove_if(clientThreads.begin(), clientThreads.end(),
                [](std::thread& t) { return !t.joinable(); }),
            clientThreads.end()
        );

        // 短暂休眠，降低CPU占用
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }

    // 停止键盘处理线程
    keyThreadRunning = false;
    keyTaskCV.notify_one();

    // 清理资源
    closesocket(listenSocket);
    WSACleanup();
    listenSocket = INVALID_SOCKET;
}

// 启动服务器
void startServer(HWND hWnd) {
    if (!serverRunning) {
        serverRunning = true;
        std::thread(serverListenThread, hWnd).detach();
    }
}

// 停止服务器
void stopServer() {
    if (serverRunning) {
        serverRunning = false;

        // 停止键盘处理线程
        keyThreadRunning = false;
        keyTaskCV.notify_one();

        // 等待所有客户端线程结束
        if (!clientThreads.empty()) {
            std::lock_guard<std::mutex> lock(threadMutex);
            for (auto& t : clientThreads) {
                if (t.joinable()) {
                    t.join();
                }
            }
            clientThreads.clear();
        }

        // 清空任务队列
        {
            std::lock_guard<std::mutex> lock(keyTaskMutex);
            keyTaskQueue.clear();
        }

        // 关闭监听套接字
        if (listenSocket != INVALID_SOCKET) {
            closesocket(listenSocket);
            listenSocket = INVALID_SOCKET;
        }
    }
}

// 预制函数
void PredefinedFunction() {
    OutputDebugString(_T("预制函数已执行，此函数可用于将来扩展功能\n"));
    _tprintf(_T("预制函数已执行，此函数可用于将来扩展功能\n"));
}

// 获取指定区域的平均颜色
COLORREF GetAverageColor(int x, int y, int size) {
    if (size <= 0) return RGB(0, 0, 0);

    // 计算区域边界
    int left = x - size;
    int top = y - size;
    int right = x + size;
    int bottom = y + size;

    // 创建兼容DC和位图
    HDC hScreenDC = GetDC(NULL);
    HDC hMemDC = CreateCompatibleDC(hScreenDC);
    HBITMAP hBitmap = CreateCompatibleBitmap(hScreenDC, right - left, bottom - top);
    HGDIOBJ hOldBitmap = SelectObject(hMemDC, hBitmap);

    // 复制屏幕区域到内存DC
    BitBlt(hMemDC, 0, 0, right - left, bottom - top, hScreenDC, left, top, SRCCOPY);

    // 计算像素总数
    int pixelCount = (right - left) * (bottom - top);
    if (pixelCount <= 0) {
        SelectObject(hMemDC, hOldBitmap);
        DeleteObject(hBitmap);
        DeleteDC(hMemDC);
        ReleaseDC(NULL, hScreenDC);
        return RGB(0, 0, 0);
    }

    // 计算平均RGB值
    DWORD totalR = 0, totalG = 0, totalB = 0;
    for (int cy = 0; cy < (bottom - top); cy++) {
        for (int cx = 0; cx < (right - left); cx++) {
            COLORREF color = GetPixel(hMemDC, cx, cy);
            totalR += GetRValue(color);
            totalG += GetGValue(color);
            totalB += GetBValue(color);
        }
    }

    // 计算平均值
    BYTE avgR = (BYTE)(totalR / pixelCount);
    BYTE avgG = (BYTE)(totalG / pixelCount);
    BYTE avgB = (BYTE)(totalB / pixelCount);

    // 清理资源
    SelectObject(hMemDC, hOldBitmap);
    DeleteObject(hBitmap);
    DeleteDC(hMemDC);
    ReleaseDC(NULL, hScreenDC);

    return RGB(avgR, avgG, avgB);
}

// 更新鼠标坐标显示
void UpdateMouseCoordinates() {
    if (!bShowCoords) return;

    // 获取输入框中的大小值
    TCHAR szSize[32];
    GetWindowText(hSizeInput, szSize, 32);
    int newSize = _ttoi(szSize);
    if (newSize > 0) {
        hSize = newSize;
    }

    POINT pt;
    if (GetCursorPos(&pt)) {
        TCHAR szCoords[64];
        _stprintf_s(szCoords, _T("鼠标坐标: X=%d, Y=%d"), pt.x, pt.y);
        SetWindowText(hCoordLabel, szCoords);

        // 获取平均颜色
        COLORREF avgColor = GetAverageColor(pt.x, pt.y, hSize);

        // 显示RGB值
        TCHAR szR[32], szG[32], szB[32];
        _stprintf_s(szR, _T("R: %d"), GetRValue(avgColor));
        _stprintf_s(szG, _T("G: %d"), GetGValue(avgColor));
        _stprintf_s(szB, _T("B: %d"), GetBValue(avgColor));

        SetWindowText(hRLabel, szR);
        SetWindowText(hGLabel, szG);
        SetWindowText(hBLabel, szB);
    }
}

// 开始鼠标跟踪
void StartMouseTracking(HWND hWnd) {
    SetTimer(hWnd, 1, 50, NULL);
    UpdateMouseCoordinates();
}

// 停止鼠标跟踪
void StopMouseTracking(HWND hWnd) {
    KillTimer(hWnd, 1);
}

// 设置钩子
void SetHook() {
    // 设置鼠标钩子
    hMouseHook = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProc, hInst, 0);
    // 设置键盘钩子
    hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardHookProc, hInst, 0);

    if (hMouseHook == NULL || hKeyboardHook == NULL) {
        MessageBox(NULL, _T("钩子设置失败！"), _T("错误"), MB_ICONEXCLAMATION | MB_OK);
    }
}

// 卸载钩子
void Unhook() {
    if (hMouseHook != NULL) {
        UnhookWindowsHookEx(hMouseHook);
        hMouseHook = NULL;
    }
    if (hKeyboardHook != NULL) {
        UnhookWindowsHookEx(hKeyboardHook);
        hKeyboardHook = NULL;
    }
}

// 更新事件日志
void UpdateEventLog(const std::wstring& event) {
    // 获取当前时间
    SYSTEMTIME st;
    GetLocalTime(&st);
    wchar_t timeStr[100];
    swprintf_s(timeStr, L"[%02d:%02d:%02d] ", st.wHour, st.wMinute, st.wSecond);

    // 添加新事件到日志
    eventLog = timeStr + event + L"\r\n" + eventLog;

    // 限制日志长度，防止内存溢出
    if (eventLog.length() > 10000) {
        eventLog = eventLog.substr(0, 10000);
    }

    // 刷新事件日志显示
    if (hEventLog) {
        SetWindowText(hEventLog, eventLog.c_str());
    }
}

// 辅助函数：获取按键对应的字符（考虑大小写）
wchar_t GetCharFromKey(DWORD vkCode, bool isExtended) {
    BYTE keyboardState[256] = { 0 };
    GetKeyboardState(keyboardState);

    // 对于字母键，强制设置键盘状态以获取正确的大小写
    if (vkCode >= 'A' && vkCode <= 'Z') {
        // 检查Shift键状态或CapsLock状态
        bool shiftPressed = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
        bool capsLockOn = (GetKeyState(VK_CAPITAL) & 0x0001) != 0;

        // 根据Shift和CapsLock状态设置键盘状态
        keyboardState[vkCode] = 0x80;
        keyboardState[VK_SHIFT] = (shiftPressed ? 0x80 : 0x00);
    }

    wchar_t buffer[2] = { 0 };
    ToUnicode(vkCode, MapVirtualKey(vkCode, MAPVK_VK_TO_VSC) | (isExtended ? 0x100 : 0),
        keyboardState, buffer, 2, 0);
    return buffer[0];
}

// 鼠标钩子过程 - 监控滚轮、左右键和移动事件
LRESULT CALLBACK MouseHookProc(int nCode, WPARAM wParam, LPARAM lParam) {
    if (nCode >= 0) {
        MSLLHOOKSTRUCT* pMouseStruct = (MSLLHOOKSTRUCT*)lParam;
        std::wstring event;
        bool shouldLog = true;

        // 处理鼠标滚轮事件
        if (wParam == WM_MOUSEWHEEL) {
            // 对于低级鼠标钩子，滚轮信息在MSLLHOOKSTRUCT的mouseData字段中
            int zDelta = GET_WHEEL_DELTA_WPARAM(pMouseStruct->mouseData);

            // 根据滚轮方向设置mouse_status
            {
                std::lock_guard<std::mutex> lock(globalVarsMutex);
                if (zDelta > 0) {
                    MOUSE_UP_OR_DOWN = 'U'; // 向上滚设置为U
                    event = L"鼠标滚轮向上滚动 - mouse_status设置为U";
                }
                else {
                    MOUSE_UP_OR_DOWN = 'D'; // 向下滚设置为D
                    event = L"鼠标滚轮向下滚动 - mouse_status设置为D";
                }
            }

            // 添加滚轮值信息用于调试
            wchar_t deltaStr[50];
            swprintf_s(deltaStr, L" (值: %d)", zDelta);
            event += deltaStr;
        }
        // 处理鼠标左键事件
        else if (wParam == WM_LBUTTONDOWN) {
            event = L"鼠标左键按下";
        }
        else if (wParam == WM_LBUTTONUP) {
            event = L"鼠标左键释放";
        }
        // 处理鼠标右键事件
        else if (wParam == WM_RBUTTONDOWN) {
            event = L"鼠标右键按下";
        }
        else if (wParam == WM_RBUTTONUP) {
            event = L"鼠标右键释放";
        }
        // 处理鼠标移动事件
        else if (wParam == WM_MOUSEMOVE) {
            // 限制移动事件记录频率，避免日志刷屏
            DWORD currentTime = GetTickCount();
            if (currentTime - lastMouseMoveTime < MOUSE_MOVE_DELAY) {
                shouldLog = false;
            }
            else {
                lastMouseMoveTime = currentTime;
                event = L"鼠标移动";
            }
        }
        // 如果不是我们关注的事件，直接传递
        else {
            return CallNextHookEx(hMouseHook, nCode, wParam, lParam);
        }

        // 记录事件
        if (shouldLog) {
            // 添加鼠标位置信息
            wchar_t posStr[100];
            swprintf_s(posStr, L" (位置: %d, %d)", pMouseStruct->pt.x, pMouseStruct->pt.y);
            event += posStr;

            UpdateEventLog(event);
        }
    }

    // 传递事件给下一个钩子
    return CallNextHookEx(hMouseHook, nCode, wParam, lParam);
}

// 键盘钩子过程 - 支持大小写区分和功能键识别
LRESULT CALLBACK KeyboardHookProc(int nCode, WPARAM wParam, LPARAM lParam) {
    if (nCode >= 0) {
        KBDLLHOOKSTRUCT* pKeyBoardStruct = (KBDLLHOOKSTRUCT*)lParam;
        bool isKeyDown = (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN);
        std::wstring eventType = isKeyDown ? L"按键按下: " : L"按键释放: ";

        // 判断是否为扩展键（如F1-F12、方向键等）
        bool isExtended = (pKeyBoardStruct->flags & LLKHF_EXTENDED) != 0;
        wchar_t keyName[256] = { 0 };
        DWORD vkCode = pKeyBoardStruct->vkCode;

        // 按下键盘z时，设置terminate_status为Y
        if (isKeyDown && vkCode == 'Z') {
            std::lock_guard<std::mutex> lock(globalVarsMutex);
            ZZZ = 'Y';
            UpdateEventLog(L"按下键盘Z键 - terminate_status设置为Y");
        }
        // 处理其他按键
        else {
            // 尝试获取功能键名称
            if (GetKeyNameTextW((LONG)(pKeyBoardStruct->scanCode << 16) | (isExtended ? 0x1000000 : 0),
                keyName, 255) > 0) {
                // 对于字母键，补充大小写信息
                if ((vkCode >= 'A' && vkCode <= 'Z')) {
                    // 正确的大小写判断逻辑：
                    // 当CapsLock开启或Shift键按下时为大写（但不同时满足时）
                    bool shiftPressed = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
                    bool capsLockOn = (GetKeyState(VK_CAPITAL) & 0x0001) != 0;
                    bool isUpperCase = shiftPressed ^ capsLockOn; // 异或运算：只有一个为真时结果为真

                    std::wstring caseInfo = isUpperCase ? L" (大写)" : L" (小写)";
                    UpdateEventLog(eventType + keyName + caseInfo);
                }
                else {
                    UpdateEventLog(eventType + keyName);
                }
            }
            // 处理常规字符键
            else if (vkCode >= 0x20 && vkCode <= 0x7E) {
                wchar_t keyChar = GetCharFromKey(vkCode, isExtended);
                wchar_t keyStr[2] = { keyChar, L'\0' };
                UpdateEventLog(eventType + keyStr);
            }
            // 处理特殊功能键
            else {
                switch (vkCode) {
                case VK_F1: UpdateEventLog(eventType + L"F1"); break;
                case VK_F2: UpdateEventLog(eventType + L"F2"); break;
                case VK_F3: UpdateEventLog(eventType + L"F3"); break;
                case VK_F4: UpdateEventLog(eventType + L"F4"); break;
                case VK_F5: UpdateEventLog(eventType + L"F5"); break;
                case VK_F6: UpdateEventLog(eventType + L"F6"); break;
                case VK_F7: UpdateEventLog(eventType + L"F7"); break;
                case VK_F8: UpdateEventLog(eventType + L"F8"); break;
                case VK_F9: UpdateEventLog(eventType + L"F9"); break;
                case VK_F10: UpdateEventLog(eventType + L"F10"); break;
                case VK_F11: UpdateEventLog(eventType + L"F11"); break;
                case VK_F12: UpdateEventLog(eventType + L"F12"); break;
                    // 其他特殊键的处理
                default:
                    swprintf_s(keyName, L"未知键 (0x%02X)", vkCode);
                    UpdateEventLog(eventType + keyName);
                    break;
                }
            }
        }
    }

    // 传递事件给下一个钩子
    return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
}

// 窗口过程函数
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
    static HWND hStaticPath;

    switch (message) {
    case WM_CREATE:
        // 创建显示文件路径的静态文本
        hStaticPath = CreateWindow(
            _T("STATIC"), szVBSFilePath,
            WS_VISIBLE | WS_CHILD | SS_LEFT,
            20, 20, 300, 20,
            hWnd, NULL, hInst, NULL
        );

        // 创建复选框
        hCheckbox = CreateWindow(
            _T("BUTTON"), _T("显示鼠标坐标"),
            WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_AUTOCHECKBOX,
            20, 50, 150, 20,
            hWnd, (HMENU)2, hInst, NULL
        );

        // 创建大小输入框标签
        hSizeLabel = CreateWindow(
            _T("STATIC"), _T("正方形大小:"),
            WS_VISIBLE | WS_CHILD | SS_LEFT,
            20, 80, 100, 20,
            hWnd, NULL, hInst, NULL
        );

        // 创建大小输入框
        hSizeInput = CreateWindow(
            _T("EDIT"), _T("2"),
            WS_TABSTOP | WS_VISIBLE | WS_CHILD | ES_NUMBER,
            120, 80, 50, 20,
            hWnd, (HMENU)3, hInst, NULL
        );

        // 创建执行按钮
        hBtnExecute = CreateWindow(
            _T("BUTTON"), _T("重启下层轰炸机"),
            WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON | BS_OWNERDRAW,
            200, 80, 130, 30,
            hWnd, (HMENU)1, hInst, NULL
        );

        // 创建坐标显示标签
        hCoordLabel = CreateWindow(
            _T("STATIC"), _T(""),
            WS_VISIBLE | WS_CHILD | SS_LEFT,
            20, 120, 300, 20,
            hWnd, NULL, hInst, NULL
        );

        // 创建RGB值显示标签
        hRLabel = CreateWindow(
            _T("STATIC"), _T("R: "),
            WS_VISIBLE | WS_CHILD | SS_LEFT,
            20, 150, 100, 20,
            hWnd, NULL, hInst, NULL
        );

        hGLabel = CreateWindow(
            _T("STATIC"), _T("G: "),
            WS_VISIBLE | WS_CHILD | SS_LEFT,
            20, 180, 100, 20,
            hWnd, NULL, hInst, NULL
        );

        hBLabel = CreateWindow(
            _T("STATIC"), _T("B: "),
            WS_VISIBLE | WS_CHILD | SS_LEFT,
            20, 210, 100, 20,
            hWnd, NULL, hInst, NULL
        );

        // 初始隐藏相关控件
        ShowWindow(hSizeLabel, SW_HIDE);
        ShowWindow(hSizeInput, SW_HIDE);
        ShowWindow(hRLabel, SW_HIDE);
        ShowWindow(hGLabel, SW_HIDE);
        ShowWindow(hBLabel, SW_HIDE);

        // 启动服务器
        startServer(hWnd);

        // 设置输入钩子
        SetHook();

        // 启动1秒定时器用于更新背景色
        SetTimer(hWnd, 2, 1000, NULL);  // 定时器ID=2，间隔1000ms
        UpdateWindowBackgroundColor(hWnd);  // 初始化背景色

        // 切换到英文输入法
        SwitchToEnglishInputMethod();
        break;

    case WM_DRAWITEM:
    {
        LPDRAWITEMSTRUCT lpdis = (LPDRAWITEMSTRUCT)lParam;
        if (lpdis->CtlID == 1) {
            // 根据当前心跳颜色选择画刷
            HBRUSH currentBrush = (HEARTBEAT_COLOR == 'R') ? hRedBrush : hGreenBrush;

            // 绘制按钮背景
            FillRect(lpdis->hDC, &lpdis->rcItem, currentBrush);

            // 设置文本颜色为白色
            SetTextColor(lpdis->hDC, RGB(255, 255, 255));
            SetBkMode(lpdis->hDC, TRANSPARENT);

            // 获取并绘制按钮文本
            TCHAR szText[256];
            GetWindowText(lpdis->hwndItem, szText, sizeof(szText) / sizeof(TCHAR));
            DrawText(lpdis->hDC, szText, -1, &lpdis->rcItem, DT_CENTER | DT_VCENTER | DT_SINGLELINE);

            // 绘制按钮状态边框
            if (lpdis->itemState & ODS_SELECTED) {
                DrawEdge(lpdis->hDC, &lpdis->rcItem, EDGE_SUNKEN, BF_RECT);
            }
            else {
                DrawEdge(lpdis->hDC, &lpdis->rcItem, EDGE_RAISED, BF_RECT);
            }
            return TRUE;
        }
        break;
    }

    // 处理按钮颜色更新消息
    case WM_USER + 1:
        UpdateButtonColor();
        break;

        // 处理窗口背景色更新消息
    case WM_USER + 2:
        UpdateWindowBackgroundColor(hWnd);
        break;

    case WM_COMMAND:
        if (LOWORD(wParam) == 1)  // 执行按钮点击事件
        {
            ExecuteExistingVBScript();
        }
        else if (LOWORD(wParam) == 2)  // 复选框点击事件
        {
            bShowCoords = IsDlgButtonChecked(hWnd, 2) == BST_CHECKED;

            if (bShowCoords) {
                // 显示相关控件
                ShowWindow(hSizeLabel, SW_SHOW);
                ShowWindow(hSizeInput, SW_SHOW);
                ShowWindow(hRLabel, SW_SHOW);
                ShowWindow(hGLabel, SW_SHOW);
                ShowWindow(hBLabel, SW_SHOW);
                StartMouseTracking(hWnd);
            }
            else {
                // 隐藏相关控件
                ShowWindow(hSizeLabel, SW_HIDE);
                ShowWindow(hSizeInput, SW_HIDE);
                ShowWindow(hRLabel, SW_HIDE);
                ShowWindow(hGLabel, SW_HIDE);
                ShowWindow(hBLabel, SW_HIDE);
                StopMouseTracking(hWnd);
                SetWindowText(hCoordLabel, _T(""));
                SetWindowText(hRLabel, _T("R: "));
                SetWindowText(hGLabel, _T("G: "));
                SetWindowText(hBLabel, _T("B: "));
            }
        }
        break;

    case WM_TIMER:
        if (wParam == 1) {
            // 定时器1事件 - 定期更新鼠标坐标和颜色信息
            UpdateMouseCoordinates();
        }
        else if (wParam == 2) {
            // 定时器2事件 - 每秒更新窗口背景色
            UpdateWindowBackgroundColor(hWnd);
        }
        break;

    case WM_DESTROY:
        // 停止服务器
        stopServer();

        // 卸载钩子
        Unhook();

        // 停止所有定时器
        KillTimer(hWnd, 1);
        KillTimer(hWnd, 2);

        // 停止鼠标跟踪
        StopMouseTracking(hWnd);
        PostQuitMessage(0);
        break;

    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}

// 检查文件是否存在
BOOL IsFileExists(LPCTSTR szPath) {
    return PathFileExists(szPath) == TRUE;
}

// 执行已存在的VBScript文件
void ExecuteExistingVBScript() {
    // 检查文件是否存在
    if (!IsFileExists(szVBSFilePath)) {
        TCHAR szMsg[512];
        _stprintf_s(szMsg, _T("找不到VBS文件:\n%s"), szVBSFilePath);
        MessageBox(NULL, szMsg, _T("文件不存在"), MB_ICONWARNING);
        return;
    }

    // 执行VBScript文件
    HINSTANCE hResult = ShellExecute(
        NULL, _T("open"), szVBSFilePath, NULL, NULL, SW_SHOWNORMAL
    );

    // 检查执行结果 - 只在失败时显示提示
    if ((int)hResult <= 32) {
        TCHAR szMsg[512];
        _stprintf_s(szMsg, _T("执行VBS文件失败，错误代码: %d"), (int)hResult);
        MessageBox(NULL, szMsg, _T("执行失败"), MB_ICONERROR);
    }
}

// WinMain 入口函数
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
    WNDCLASSEX wcex;

    // 创建红色和绿色画刷（按钮用）
    hRedBrush = CreateSolidBrush(RGB(255, 0, 0));
    hGreenBrush = CreateSolidBrush(RGB(0, 255, 0));

    // 创建窗口背景用的画刷（使用半透明效果）
    hWindowRedBrush = CreateSolidBrush(RGB(255, 200, 200));   // 浅红色
    hWindowGreenBrush = CreateSolidBrush(RGB(200, 255, 200)); // 浅绿色

    wcex.cbSize = sizeof(WNDCLASSEX);
    wcex.style = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc = WndProc;
    wcex.cbClsExtra = 0;
    wcex.cbWndExtra = 0;
    wcex.hInstance = hInstance;
    wcex.hIcon = LoadIcon(hInstance, IDI_APPLICATION);
    wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    wcex.lpszMenuName = NULL;
    wcex.lpszClassName = szWindowClass;
    wcex.hIconSm = LoadIcon(wcex.hInstance, IDI_APPLICATION);

    // 设置初始窗口标题，包含端口号
    _stprintf_s(szTitle, _T("顶层轰炸机 (端口 %d)"), SERVER_PORT);

    if (!RegisterClassEx(&wcex)) {
        MessageBox(NULL, _T("窗口注册失败！"), _T("错误"), NULL);
        return 0;
    }

    hInst = hInstance;

    // 获取屏幕工作区大小（排除任务栏）
    RECT desktopRect;
    SystemParametersInfo(SPI_GETWORKAREA, 0, &desktopRect, 0);

    // 窗口宽度和高度
    int windowWidth = 350;
    int windowHeight = 280;

    // 计算窗口位置
    int xPos = desktopRect.right - windowWidth - 10;
    int yPos = desktopRect.top + 280;

    // 确保窗口不会超出屏幕边界
    if (xPos < desktopRect.left + 10) {
        xPos = desktopRect.left + 10;
    }
    if (yPos + windowHeight > desktopRect.bottom) {
        yPos = desktopRect.bottom - windowHeight - 10;
    }

    // 创建窗口
    HWND hWnd = CreateWindowEx(
        WS_EX_LAYERED,
        szWindowClass,
        szTitle,
        WS_OVERLAPPEDWINDOW & ~WS_THICKFRAME & ~WS_MAXIMIZEBOX,
        xPos, yPos, windowWidth, windowHeight,
        NULL,
        NULL,
        hInstance,
        NULL
    );

    if (!hWnd) {
        MessageBox(NULL, _T("创建窗口失败！"), _T("错误"), NULL);
        DeleteObject(hRedBrush);
        DeleteObject(hGreenBrush);
        DeleteObject(hWindowRedBrush);
        DeleteObject(hWindowGreenBrush);
        return 0;
    }

    // 设置窗口透明度为30%
    SetLayeredWindowAttributes(hWnd, 0, 77, LWA_ALPHA);

    // 设置窗口置顶
    SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);

    ShowWindow(hWnd, nCmdShow);
    UpdateWindow(hWnd);

    // 调用预制函数
    PredefinedFunction();

    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    // 清理资源
    DeleteObject(hRedBrush);
    DeleteObject(hGreenBrush);
    DeleteObject(hWindowRedBrush);
    DeleteObject(hWindowGreenBrush);
    return (int)msg.wParam;
}
